import logging
import pymongo
logger = logging.getLogger(__name__)


class AaaPipeline:
    def __init__(self, mongo_uri, mongo_db, project_name, sample_name):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
        self.project_name = project_name
        self.sample_name = sample_name

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE'),
            project_name=crawler.settings.get('PROJECT_COLLECTION'),
            sample_name=crawler.settings.get('SAMPLE_COLLECTION'),
        )
    
    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]
        self.project_collection = self.db[self.project_name]
        self.sample_collection = self.db[self.sample_name]
        spider.logger.info('[AaaPipeline] connect mongo')

    def close_spider(self, spider):
        self.client.close()
        spider.logger.info('[AaaPipeline] close mongo')

    def process_item(self, item, spider):
        if 'sample_codes' in item:
            # 使用upsert更新或插入
            self.sample_collection.update_one(
                {'folder_id': item['folder_id']},
                {'$set': item},
                upsert=True
            )
        if 'method_details' in item:
            # 使用upsert更新或插入
            self.project_collection.update_one(
                {'id': item['id']},
                {'$set': item},
                upsert=True
            )
        return item
